package cn.hxt.user.service.impl;

import cn.hxt.basic.constant.BaseConstants;
import cn.hxt.basic.exception.BusinessException;
import cn.hxt.basic.util.AjaxResult;
import cn.hxt.basic.util.HttpClientUtils;
import cn.hxt.basic.util.MD5Utils;
import cn.hxt.basic.util.StrUtils;
import cn.hxt.user.domain.Logininfo;
import cn.hxt.user.domain.User;
import cn.hxt.user.domain.WxUser;
import cn.hxt.user.dto.LoginDto;
import cn.hxt.user.mapper.LogininfoMapper;
import cn.hxt.user.mapper.UserMapper;
import cn.hxt.user.mapper.WxUserMapper;
import cn.hxt.user.service.ILoginService;
import com.alibaba.fastjson.JSONObject;
import com.sun.xml.internal.bind.v2.TODO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 账号登录
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> accountLogin(LoginDto dto) {
        //校验type
        if(dto.getType() == null){
            throw new BusinessException("type一定要填！！！！");
        }
        //查询用户名再数据库中是否存在
        Logininfo logininfo = logininfoMapper.loadByUserName(dto);
        if (logininfo==null){
            throw new BusinessException("用户名不存在!!!!!!");
        }
        //判断密码是否一致，加盐后的，dto中有之前传的盐，自接取就行
        String salt = logininfo.getSalt();
        String md = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        if (logininfo.getPassword().equals(md)){
            throw new BusinessException("密码错误！！！");
        }
        //登录成功，保存到redis中
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,
                logininfo,
                30,
                TimeUnit.MINUTES);

        //返回成功必要信息
        Map<String,Object> map = new HashMap<>();
        map.put("token", token);
        //将敏感字符屏蔽掉，例如密码，账号。。。。
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        map.put("logininfo", logininfo);
        return map;
    }


    //微信登录
    @Override
    public AjaxResult wechat(String code) {
        //校验code是否有值
        if (StringUtils.isEmpty(code)){
            throw new BusinessException("code不能为空喔！！！！");
        }
        //通过code获取token和openId，把常量放到之前抽取的常量类中，使用.replace替换
        String tokenUrl  = BaseConstants.GET_TOKEN_URL
                .replace("APPID", BaseConstants.APPID)
                .replace("SECRET", BaseConstants.SECRET)
                .replace("CODE", code);
        //使用Http工具类发送请求，请求返回string
        String tokenObjStr  = HttpClientUtils.httpGet(tokenUrl);
        //将string转为json，并从中获取字段accessToken 和openId
        JSONObject jsonObject = JSONObject.parseObject(tokenObjStr);
        String accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");

        //再用openId 去查询t_wxuser
        WxUser wxUser = wxUserMapper.loadByOpenId(openId);
        //判断wxuser有没有信息
        if (wxUser!=null){
            //如果wxuser不为空，说明有注册过，免密登录
            //通过wxuser中的user_id获取logininfo
            Logininfo logininfo = logininfoMapper.loadByUserId(wxUser.getUser_id());
            //盐值
            String token = UUID.randomUUID().toString();
            //redis保存
            redisTemplate.opsForValue().set(
                    token,
                    logininfo,
                    30,
                    TimeUnit.MINUTES);

            //返回成功必要信息
            Map<String,Object> map = new HashMap<>();
            map.put("token", token);
            //将敏感字符屏蔽掉，例如密码，账号。。。。
            logininfo.setPassword(null);
            logininfo.setSalt(null);
            map.put("logininfo", logininfo);
            return AjaxResult.me().setResultObj(map);
        }else {
            //如果为空，说明第一次来，就拼接跳转到绑定页面
            String binderParams = "?accessToken="+accessToken+"&openId="+openId;
            return AjaxResult.me().setSuccess(false).setResultObj(binderParams);
        }
    }

    //微信绑定
    @Override
    public Map<String,Object> binderWechat(Map<String, String> params) {
        //校验
        //获取数据
        String phone = params.get("phone");
        String verifyCode = params.get("verifyCode");
        String accessToken = params.get("accessToken");
        String openId = params.get("openId");
        //判断是否有值
        if (StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(verifyCode)
                || StringUtils.isEmpty(accessToken)
                || StringUtils.isEmpty(openId)){
            throw new BusinessException("不要忘了哪没填！！");
        }
        //获取验证码一扒拉
        Object codeTmp = redisTemplate.opsForValue().get(BaseConstants.BUSINESS_BINDER_PREFIX + phone);
        //判断验证码是否过期，有说明没过期
        if (codeTmp  == null){
            throw new BusinessException("验证码已过期，请重新获取！！！！");
        }
        //截取验证码
        String code = ((String)codeTmp ).split(":")[0];
        //判断用户输的验证码是否一致
        if (!verifyCode.equalsIgnoreCase(code)){
            throw new BusinessException("请输入正确的验证码！！");
        }
        //查询手机号是否注册
        User user = userMapper.loadByPhone(phone);
        Logininfo logininfo = null;
        if (user != null){
            //注册了，就查询出他的微信信息做绑定，获取logininfo
            logininfo = logininfoMapper.loagById(user.getLogininfo_id());
        }else {
            //创建一个新的
            user = login2user(phone);
            //user转logininfo
            logininfo = user2logininfo(user);
            // 1.保存logininfo
            logininfoMapper.save(logininfo);//返回自增id
            // 2.保存 user
            user.setLogininfo_id(logininfo.getId());
            userMapper.save(user);
        }
        //调用微信，获取用户信息，替换属性内容
        String getWxUserURL = BaseConstants.GET_WXUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        //发送http
        String wxUserStr = HttpClientUtils.httpGet(getWxUserURL);
        //将wxUserStr自接转成WxUser，让WxUser中的属性有值
        WxUser wxUser = JSONObject.parseObject(wxUserStr, WxUser.class);
        wxUser.setUser_id(user.getId());//绑定用户
        wxUserMapper.save(wxUser);
        //免密登录
        //盐值
        String token = UUID.randomUUID().toString();
        //redis保存
        redisTemplate.opsForValue().set(
                token,
                logininfo,
                30,
                TimeUnit.MINUTES);

        //返回成功必要信息
        Map<String,Object> map = new HashMap<>();
        map.put("token", token);
        //将敏感字符屏蔽掉，例如密码，账号。。。。
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        map.put("logininfo", logininfo);
        return map;
    }






    private User login2user(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        //盐值
        String code = StrUtils.getComplexRandomString(32);
        //加盐密码              设置默认密码
        String md = MD5Utils.encrypByMd5("1" + code);
        //按道理应该再这给客户发送短信告诉他默认密码是多少
        //  TODO   发送短信给客户
        user.setSalt(code);
        user.setPassword(md);
        return user;
    }

    private Logininfo user2logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //使用spring给我们提供的Util
        // 拷贝相同字段内容     拷贝user再logininfo中有的字段内容
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }
}
